﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PinWin.Properties;

namespace PinWin
{
	public class TopProcess : IDisposable
	{
		NotifyIcon ni;
		public TopProcess()
		{
			ni = new NotifyIcon();
		}

		public void Display()
		{
			ni.MouseClick += new MouseEventHandler(ni_MouseClick);
			ni.Icon = Resources.TrayIcon;
			ni.Text = "Pin Window To Top";
			ni.Visible = true;

			ni.ContextMenuStrip = new ContextMenu().Create();
		}

		public void Dispose()
		{
			ni.Dispose();
		}

		void ni_MouseClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
			
			}
		}


		public static List<WindowInfo> GetAllProcesses()
		{
			Process[] procs = Process.GetProcesses();
			IntPtr hWnd;

			int currentID = Process.GetCurrentProcess().Id;

			List<WindowInfo> wi = new List<WindowInfo>();

			foreach (Process proc in procs)
			{
				if ((hWnd = proc.MainWindowHandle) != IntPtr.Zero && currentID != proc.Id && proc.ProcessName.ToLower() != "explorer")
				{
					try
					{						
						wi.Add(new WindowInfo(proc.Id, proc.Handle, hWnd, proc.ProcessName, proc.MainWindowTitle, proc.MainWindowHandle));
					}
					catch { }
				}
			}

			return wi;
		}

		public static void SetTopMode(object wrapper, IntPtr hWnd, IntPtr mode, bool useTransp)
		{
			try
			{
				WindowsMessageHelper.RECT rect = new WindowsMessageHelper.RECT();

				int alpha = 255;
				if (mode == WindowsMessageHelper.HWND.TOPMOST)
				{
					if (WindowsMessageHelper.IsIconic(hWnd))
					{
						WindowsMessageHelper.ShowWindowAsync(hWnd, WindowsMessageHelper.SW_RESTORE);
					}
					WindowsMessageHelper.ShowWindowAsync(hWnd, WindowsMessageHelper.SW_SHOW);

					WindowsMessageHelper.SetForegroundWindow(hWnd);
					WindowsMessageHelper.BringWindowToTop(hWnd);
				}
				
				
				WindowsMessageHelper.GetWindowRect(new HandleRef(wrapper, hWnd), out rect);

				WindowsMessageHelper.SetWindowPos(hWnd, mode, rect.X, rect.Y, rect.Width, rect.Height, (uint)WindowsMessageHelper.SWP.SHOWWINDOW);

				if (useTransp)
				{
					alpha = 165;
				}
				
				WindowsMessageHelper.SetWindowLong(
					hWnd, WindowsMessageHelper.GWL_EXSTYLE,
					WindowsMessageHelper.GetWindowLong(hWnd, WindowsMessageHelper.GWL_EXSTYLE) | WindowsMessageHelper.WS_EX_LAYERED);
				WindowsMessageHelper.SetLayeredWindowAttributes(hWnd, 0, (byte)alpha, WindowsMessageHelper.LWA_ALPHA);
				
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}
	}
}
